package com.wjv.example.springboot.base.filter;

import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


/**
 * <p>Title: HttpServletRequestFilter</p>
 *
 * Request请求过滤器
 *
 * @author wjv
 */
@Component
@WebFilter(filterName = "HttpServletRequestFilter", urlPatterns = "/")
@Order(10000)
public class HttpServletRequestFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;

        if (servletRequest instanceof HttpServletRequest) {
            String contentType = servletRequest.getContentType();
            if (contentType != null) {
                if (contentType.startsWith(MediaType.APPLICATION_JSON_VALUE) ||
                        contentType.startsWith(MediaType.APPLICATION_XML_VALUE)) {
                    requestWrapper = new RequestWrapper((HttpServletRequest) servletRequest);
                }
            }
        }
        // 获取请求中的流如何，将取出来的字符串，再次转换成流，然后把它放入到新request对象中
        // 在chain.doFiler方法中传递新的request对象
        if (requestWrapper == null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            filterChain.doFilter(requestWrapper, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}

